import { QuestionItem } from "./components/QuestionItem";
import { all_questions } from "./questions";
import { WaterMark } from "./components/WaterMark";
import { useState } from "react";
import { Question } from "./interface";

interface StoreQuestions {
    questions: Question[],
    content: string
}
const STORE_KEY = 'store_questions'
const store_questions_str = localStorage.getItem(STORE_KEY)
const store_questions: StoreQuestions | null = store_questions_str ? JSON.parse(store_questions_str) : null

const App = () => {
    const [content, setContent] = useState(store_questions?.content || '')
    const [questions, setQuestions] = useState<StoreQuestions | null>(store_questions)
    const [counts, setCounts] = useState<Record<string, number>>(all_questions.reduce((acc, { key }) => ({
        ...acc,
        [key]: 2
    }), {}))

    const handleGenerate = () => {
        const totalCount = Object.values(counts).reduce((a, b) => a + b, 0)
        if (totalCount === 0) {
            alert('请至少选择一种类型的题目')
            return
        }

        const selectedQuestions: Question[] = []
        all_questions.forEach(({ key, questions: typeQuestions }) => {
            const count = counts[key] || 0
            if (count > 0) {
                const shuffled = [...typeQuestions].sort(() => Math.random() - 0.5)
                selectedQuestions.push(...shuffled.slice(0, count))
            }
        })

        const result = {
            content,
            questions: selectedQuestions
        }

        localStorage.setItem(STORE_KEY, JSON.stringify(result))
        setQuestions(result)
    }

    if (!questions) {
        return <div className="w-md mx-auto mt-16">
            <div className="bg-white p-6 rounded-lg shadow-lg border border-gray-200">
                <h2 className="text-2xl text-center pb-3">生成测试题</h2>
                <div className="flex flex-col gap-2">
                    <form action="" onSubmit={handleGenerate}>
                        <div className="relative">
                            <input 
                                type="text" 
                                className="w-full px-2 py-1 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                                placeholder="请输入水印文案"
                                value={content}
                                onChange={e => setContent(e.target.value)}
                            />
                        </div>
                        <div className="flex flex-col gap-1">
                            {all_questions.map(({ key, title, questions: typeQuestions }, index) => (
                                <div key={key} className="flex items-center gap-2">
                                    <label className="flex-1 text-gray-700">{index + 1}. {title}</label>
                                    <div className="flex items-center gap-1">
                                        <input 
                                            type="range" 
                                            min={0} 
                                            max={10}
                                            style={{
                                                width: 200
                                            }}
                                            value={counts[key] || 0}
                                            onChange={e => setCounts(prev => ({
                                                ...prev,
                                                [key]: parseInt(e.target.value) || 0
                                            }))}
                                        />
                                        <span className="text-gray-600 inline-block w-10 text-right">{counts[key] || 0}题</span>
                                    </div>
                                </div>
                            ))}
                        </div>
                        <div className="flex justify-center">
                            <button 
                                className="px-8 py-1 bg-blue-500 text-white rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-all text-lg"
                                onClick={handleGenerate}
                            >生成</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    }

    return (
        <ol className="container mx-auto pl-6">
            <h1 className="text-2xl text-center p-2 pb-4">
                <span>前端技能测试</span>
                <a className="text-sm ml-4 text-blue-500 print:hidden" href="javascript:void(0)" onClick={() => {
                    if (confirm('确定要重新生成吗？')) {
                        localStorage.removeItem(STORE_KEY)
                        setQuestions(null)
                    }
                }}>重新生成</a>
            </h1>
            <div className="overflow-hidden hidden print:block">
                <p className="float-right h-10">
                    姓名: <span className="inline-block w-20 border-b border-solid"></span>
                </p>
            </div>
            {questions.questions.map((question, index) => (
                <QuestionItem key={index} item={question} index={index} />
            ))}
            <WaterMark content={content + ' ' + new Date().toLocaleDateString()} />
        </ol>
    )
}

export default App;
